package spark.mgworkplace.job.udf

import java.math.RoundingMode
import java.sql.Timestamp
import java.text.{NumberFormat, SimpleDateFormat}
import java.util.{Calendar, Date}

/**
  *
  * @author eureka.wh
  * @since 2019/6/15
  */
object TransformKit {

  // Double类型保留N位小数(注:如果Double先转字符串，再substirng方法截取10位，最后再toDouble，对于13位时间戳，存在精度丢失的问题)
  def doubleRetainDecimal = (number: Double, retainedDigit: Int, roundingMode: RoundingMode) => {
    val nf = NumberFormat.getNumberInstance
    nf.setMaximumFractionDigits(retainedDigit)
    // 四舍五入方式取整
    nf.setRoundingMode(roundingMode)
    nf.format(number).toDouble
  }

  /**
    * TimeStamp ---> String,
    * stringType常见格式：
    * 1、"yyyy-MM-dd HH:mm:ss"
    * 2、"yyyy-MM-dd"
    * 3、"HH:mm:ss"  hh表示12小时制度、HH表示24小时制
    */
  def timeStamp2String(timeStamp: Timestamp, stringType: String = "yyyy-MM-dd HH:mm:ss") = {
    var timeStr = ""
    try {
      val sdf = new SimpleDateFormat(stringType)
      timeStr = sdf.format(timeStamp)
    } catch {
      case e: NullPointerException => println(e.getMessage)
      case e: Exception => println(e.getMessage)
    }
    timeStr
  }

  // String ---> TimeStamp
  def string2Timestamp = (timeStr: String) => {
    var timestamp: Timestamp = Timestamp.valueOf("1970-01-01 00:00:00")
    try {
      timestamp = Timestamp.valueOf(timeStr)
    } catch {
      case e: java.lang.IllegalArgumentException => println(e.getMessage)
      case e: Exception => println(e.getMessage)
    }
    timestamp
  }

  // Date ---> TimeStamp
  def date2TimeStamp = (date: Date) => {
    if (date == null) throw new NullPointerException("the parameter 'date' is null")
    val tmsp = new Timestamp(date.getTime)
    tmsp
  }

  // Date ---> String
  def date2String(date: Date, stringType: String = "yyyy-MM-dd HH:mm:ss") = {
    if (date == null) throw new NullPointerException("the parameter 'date' is null")
    timeStamp2String(date2TimeStamp(date), stringType)
  }

  // 日期增加减少,返回TimeStamp
  def timeStampChangeRetTmsp(timestamp: Timestamp, changedValue: Int = 1, changedType: Int = 6 /* DAY_OF_YEAR = 6 、DAY_OF_MONTH = 5 */) = {
    if (timestamp == null) throw new NullPointerException("the parameter 'timestamp' is null")
    val calendar = Calendar.getInstance()
    calendar.setTime(timestamp)
    calendar.add(Calendar.DAY_OF_YEAR, changedValue)
    date2TimeStamp(calendar.getTime)
  }

  // 日期增加减少,返回String
  def timeStampChangeRetStr(timestamp: Timestamp, changedValue: Int = 1, changedType: Int = 6 /* DAY_OF_YEAR = 6 、DAY_OF_MONTH = 5 */) = {
    if (timestamp == null) throw new NullPointerException("the parameter 'timestamp' is null")
    val calendar = Calendar.getInstance()
    calendar.setTime(timestamp)
    calendar.add(Calendar.DAY_OF_YEAR, changedValue)
    date2String(calendar.getTime)
  }
}
